import { Button, DatePicker, Form, Icon, Input, Select, Table } from 'antd';
import React, { ReactNode } from 'react';
import { withRouter } from 'react-router-dom';
import { connect } from 'dva';
import _ from 'lodash';
import moment, { Moment } from 'moment';
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';
import ReviewDialog from './components/reviewDialog';

import styles from './style.less';
import * as tools from '@/utils/tools';
import { REVIEW_TYPE, PAGE_SIZE_OPTION } from '../data';
import { getReviewColumns } from './utils';
import { initialTimeWithMill, checkHasChanged, StateType, PropType } from '../utils';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { Option } = Select;

// 初始化表头筛选数据
function initTableFilters() {
  return {
    userType: '-1',
    keywords: undefined,
    userName: undefined,
    reallyName: undefined,
    auditor: undefined,
  };
}

class Review extends React.PureComponent<PropType, StateType> {
  public state: StateType = {
    payload: {
      size: 20,
      page: 1,
    },
    reviewDialogVisible: false,
    reviewRow: {},
    tableFilters: initTableFilters(),
    imgViewDialogVisible: false,
    imgList: [],
    loading: false,
    errTip: false,
  };

  componentDidMount() {
    this.bindEffects();
    this.getReviewerListEffect();
    this.getManageListEffect();
  }

  private getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ confirm, clearFilters }) => (
      <div style={{ padding: '8px' }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          value={this.state.tableFilters[dataIndex]}
          onChange={e => {
            const state = _.cloneDeep(this.state);
            state.tableFilters[dataIndex] = e.target.value;
            this.setState({
              ...state,
            });
          }}
          onPressEnter={() => this.bindEffects(confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
          allowClear
        />
        {/* 搜索 */}
        <Button
          type="primary"
          onClick={() => {
            const { payload } = this.state;
            this.setState({ payload: { ...payload, page: 1 } }, () => this.bindEffects(confirm));
          }}
          icon="search"
          size="small"
          style={{ width: 90, marginLeft: '0px' }}
        >
          {formatMessage({ id: 'recharge-review.table.search-btn' })}
        </Button>
        {/* 重置 */}
        <Button
          onClick={() => {
            clearFilters();
            const { tableFilters } = this.state;
            const tableFiltersData = { ...tableFilters };
            tableFiltersData[dataIndex] = '';
            const { payload } = this.state;
            this.setState(
              {
                payload: { ...payload, page: 1 },
                tableFilters: tableFiltersData,
              },
              () => this.bindEffects(confirm),
            );
          }}
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          {formatMessage({ id: 'recharge-review.table.reset-btn' })}
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
  });

  // 获取列表
  private bindEffects = (confirm?: any) => {
    if (confirm) confirm();
    const { page, size } = this.state.payload;
    const params = this.props.form.getFieldsValue();
    const obj = tools.handleSendData({ ...this.state.tableFilters, ...params });

    this.props.dispatch({
      type: 'recharge/reviewDataEffect',
      payload: {
        page,
        size,
        userType: -1,
        ...obj,
      },
      callback: () => this.setState({ loading: false }),
    });
    this.setState({ loading: true });
  };

  // 获取申请人
  private getReviewerListEffect = () => {
    this.props.dispatch({
      type: 'recharge/reviewerListEffect',
    });
  };

  // 获取审核人
  private getManageListEffect = () => {
    this.props.dispatch({
      type: 'recharge/getReviewManageListEffect',
    });
  };

  // 表格onChange
  private onTableChange = (pagination: any, filters: any[], sorter?: any) => {
    const { current, pageSize } = pagination;
    const tableFilters = { ...this.state.tableFilters };
    const hasChanged = filters ? checkHasChanged(tableFilters, filters) : false;

    Object.keys(filters).forEach(key => {
      const { length } = filters[key];
      const str = length > 1 ? filters[key].join(',') : filters[key]['0'];
      const dataStr = length > 1 ? str.substring(0, str.length - 1) : str;
      if (key === 'sucReqOperator') {
        tableFilters.applicant = dataStr;
      } else {
        tableFilters[key] = dataStr;
      }
    });

    this.setState(
      {
        tableFilters: { ...tableFilters },
        payload: {
          page: hasChanged ? 1 : current,
          size: pageSize,
        },
      },
      () => this.bindEffects(),
    );
  };

  // 关闭审核弹窗
  private handleDialogClose = () => {
    this.setState({
      reviewDialogVisible: false,
    });
  };

  // 审核确认
  private handleDialogConfirm = () => {
    this.setState({
      reviewDialogVisible: false,
    });
    this.bindEffects();
  };

  // 点击审核
  private handleReview = (record: object) => {
    this.setState({
      reviewRow: record,
      reviewDialogVisible: true,
    });
  };

  // 搜索
  private handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const time = this.props.form.getFieldValue('time');
    const orderId = this.props.form.getFieldValue('orderId').trim();
    if (!this.checkTimeAndOrderId(time, orderId)) {
      this.setState({ errTip: true });
    } else {
      this.setState({ page: 1 }, () => {
        this.bindEffects();
      });
    }
  };

  // 重置
  private handleReset = () => {
    this.props.form.resetFields();
    const payload = { page: 1, size: 20 };
    const state = { ...this.state, payload, errTip: false };
    state.tableFilters = initTableFilters();
    this.setState({ ...state }, () => {
      this.bindEffects();
    });
  };

  // 检测时间和订单号，必须填一个
  private checkTimeAndOrderId = (time: Moment[], orderId: string) => {
    const { errTip } = this.state;
    let flag: boolean;
    if (time.length < 1 && !orderId && !errTip) {
      flag = true;
    }
    if ((time.length > 0 || orderId) && errTip) {
      flag = false;
    }
    this.setState({ errTip: flag });
    return !flag;
  };

  // 渲染表单
  private renderFilters = () => {
    const { getFieldDecorator } = this.props.form;
    const { errTip } = this.state;
    let tip = {
      timeTip: {},
      orderIdTip: {},
    };
    if (errTip) {
      tip = {
        timeTip: {
          help: '请选择提交时间',
          validateStatus: 'error',
        },
        orderIdTip: {
          help: '请输入充值单号',
          validateStatus: 'error',
        },
      };
    }

    return (
      <Form layout="inline" onSubmit={this.handleSubmit} style={{ marginBottom: '20px' }}>
        {/* 提交时间： */}
        <FormItem
          label={<FormattedMessage id="recharge-review.filters.commit-time" />}
          {...tip.timeTip}
        >
          {getFieldDecorator('time', {
            initialValue: initialTimeWithMill(30),
          })(
            <RangePicker
              format="YYYY-MM-DD HH:mm:ss"
              placeholder={['开始时间', '结束时间']}
              showTime={{
                hideDisabledOptions: true,
                defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
              }}
              onChange={(dates: Moment[]) => {
                const orderId = this.props.form.getFieldValue('orderId').trim();
                this.checkTimeAndOrderId(dates, orderId);
              }}
            />,
          )}
        </FormItem>

        {/* 充值单号： */}
        <FormItem
          label={<FormattedMessage id="recharge-review.filters.order-id" />}
          {...tip.orderIdTip}
        >
          {getFieldDecorator('orderId', {
            initialValue: '',
          })(
            <Input
              placeholder="请输入充值单号"
              allowClear
              onChange={(e: any) => {
                const { value } = e.target;
                const orderId = value.trim();
                const time = this.props.form.getFieldValue('time');
                this.checkTimeAndOrderId(time, orderId);
              }}
            />,
          )}
        </FormItem>

        {/* 审核记录 */}
        <FormItem label={<FormattedMessage id="recharge-review.filters.recharge-record" />}>
          {getFieldDecorator('approveStatus', {
            initialValue: -1,
          })(
            <Select style={{ width: 120 }}>
              {REVIEW_TYPE.map(item => (
                <Option value={item.value} key={item.value}>
                  {item.title}
                </Option>
              ))}
            </Select>,
          )}
        </FormItem>

        <FormItem>
          {/* 搜索 */}
          <Button type="primary" htmlType="submit" disabled={errTip}>
            {formatMessage({ id: 'recharge-review.filters.search-btn' })}
          </Button>
          {/* 重置 */}
          <Button onClick={this.handleReset}>
            {formatMessage({ id: 'recharge-review.filters.reset-btn' })}
          </Button>
        </FormItem>
      </Form>
    );
  };

  // 渲染表格
  private renderTable = () => {
    const { loading, payload } = this.state;
    const { size, page } = payload;
    const { reviewData } = this.props.recharge;

    return (
      <Table
        loading={loading}
        className={styles.tableStyle}
        bordered
        rowKey={(record: any) => record.orderId}
        columns={getReviewColumns(this)}
        dataSource={reviewData.list}
        scroll={{ x: 1800, y: 540 }}
        onChange={(pagination, filters, sorter) => this.onTableChange(pagination, filters, sorter)}
        pagination={{
          total: reviewData.total,
          pageSize: size,
          current: page,
          onShowSizeChange: this.handleSizeChange,
          showSizeChanger: true,
          showQuickJumper: true,
          pageSizeOptions: PAGE_SIZE_OPTION,
          showTotal: () =>
            `共 ${reviewData.total}条记录 第 ${page} / ${Math.ceil(reviewData.total / size)}`,
        }}
      />
    );
  };

  public render(): ReactNode {
    const { reviewRow, reviewDialogVisible } = this.state;

    return (
      <div className={styles.reviewContainer}>
        {this.renderFilters()}
        {this.renderTable()}
        {reviewDialogVisible && !_.isEmpty(reviewRow) ? (
          <ReviewDialog<>
            data={reviewRow}
            confirm={this.handleDialogConfirm}
            close={this.handleDialogClose}
            visible={reviewDialogVisible}
          />
        ) : null}
      </div>
    );
  }
}

const ReviewContainer = Form.create({ name: 'rechargeReview' })(Review);

export default withRouter(
  connect(({ recharge, global }: { recharge: any }) => ({
    recharge,
    btns: global.btns,
  }))(ReviewContainer),
);
